package com.havey.ye.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.havey.ye.dto.CommonResponseDTO;
import com.havey.ye.dto.UserInfoDTO;
import com.havey.ye.entity.UserInfo;
import com.havey.ye.service.IUserInfoService;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yehuaiwei
 * @since 2025-01-23
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private IUserInfoService iUserInfoService;

    @PostMapping("/submit")
    @ResponseBody
    public CommonResponseDTO<Integer> submit(@RequestBody UserInfoDTO user) {
        String username = user.getUserName();
        String password = user.getPassword();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUsername, username);
        queryWrapper.eq(UserInfo::getPasswordHash, password);
        UserInfo foundUser = iUserInfoService.getOne(queryWrapper);
        if (foundUser == null) {
            return CommonResponseDTO.failure(403, "用户名或者密码错误");
        }
        return CommonResponseDTO.success(foundUser.getUserId()); // 表示登录失败
    }

    /**
     * 1. 注册接口，入参是UserInfoDTO，返回值是CommonResponseDTO<Integer>
     * 2. 注册校验用户名是否重复，如果重复，返回CommonResponseDTO.failure(403, "用户名重复")
     * 3. 注册成功，返回CommonResponseDTO.success(userId)
     */
    @PostMapping("/register")
    @ResponseBody
    public CommonResponseDTO<Integer> register(@RequestBody UserInfoDTO user) {
        String username = user.getUserName();
        String password = user.getPassword();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUsername, username);
        UserInfo foundUser = iUserInfoService.getOne(queryWrapper);
        if (foundUser != null) {
            return CommonResponseDTO.failure(403, "用户名重复");
        }
        UserInfo newUser = new UserInfo();
        newUser.setUsername(username);
        newUser.setPasswordHash(password);
        iUserInfoService.save(newUser);
        return CommonResponseDTO.success(newUser.getUserId());
    }
}
